package com.jwdf.uda.ui.fragment.question;

import android.annotation.TargetApi;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jwdf.uda.R;
import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.databinding.LayQuizBinding;
import com.jwdf.uda.databinding.PopQuizBinding;
import com.jwdf.uda.event.FindSwitchEvent;
import com.jwdf.uda.event.LongTaskEvent;
import com.jwdf.uda.ui.activity.LongTaskList;
import com.jwdf.uda.ui.activity.NewProblemsActivity;
import com.jwdf.uda.ui.activity.SearchActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.progress.LongTask;
import com.jwdf.uda.ui.fragment.question.index.QuizConcernFragment;
import com.jwdf.uda.ui.fragment.question.index.QuizHotFragment;
import com.jwdf.uda.ui.fragment.question.index.QuizMineFragment;
import com.jwdf.uda.ui.fragment.question.index.QuizNewFragment;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;

import static android.databinding.DataBindingUtil.bind;

/**
 * Created by RD-001 on 2016/4/27.
 */
public class QuizFragment extends BaseFragment {

    public static final String TAG = QuizFragment.class.getSimpleName();
    LayQuizBinding mDataBinding;
    private RotateAnimation mRotateAnimation;
    private RotateAnimation mReverseAnimation;
    private PopupWindow mDropDownMenu;
    private int mRotateDuration = 150;
    private int menuWidth;
    private ImageView mArrowRotate;
    private LinearLayout mTileLayout;
    private TextView tvTitle;
    private TextView vSel;
    public QuizFragment() {}
    public static QuizFragment instance() {
        QuizFragment view = new QuizFragment();
        return view;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }
    @Override
    public void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = LayQuizBinding.inflate(inflater, container, false);
        setupContentView();
        return mDataBinding.getRoot();
    }
    private void setupContentView() {
        createAnimation();

        LinearLayout.LayoutParams flParams = (LinearLayout.LayoutParams) mDataBinding.quizTitle.getLayoutParams();
        flParams.height += DisplayUtils.getStatusBarHeight(getContext());
        mDataBinding.quizTitle.setLayoutParams(flParams);
        mDataBinding.llFilterTitle.setPadding(0, DisplayUtils.getStatusBarHeight(getContext()), 0, 0);
        mDataBinding.flHeadAction.setPadding(DisplayUtils.dipToPix(getContext(),15), DisplayUtils.getStatusBarHeight(getContext()), DisplayUtils.dipToPix(getContext(),15), 0);
        mDataBinding.flFindSearch.setPadding(DisplayUtils.dipToPix(getContext(),15), DisplayUtils.getStatusBarHeight(getContext()), DisplayUtils.dipToPix(getContext(),15), 0);
        mArrowRotate = mDataBinding.vArrow;
        tvTitle = mDataBinding.tvTitle;
        mTileLayout = mDataBinding.llFilterTitle;

        mTileLayout.setOnClickListener(createOnClickListener());
        mDataBinding.flHeadAction.setOnClickListener(createOnClickListener());
        mDataBinding.flFindSearch.setOnClickListener(createOnClickListener());
        mDataBinding.btnLongtask.setOnClickListener(createOnClickListener());
        listAdd();

    }

    private void listAdd() {

        View vPop = LayoutInflater.from(getContext()).inflate(R.layout.pop_quiz, null);
        final PopQuizBinding mBingding = bind(vPop);

        final TextView tvNew = mBingding.tvNew;
        tvNew.setTag(new QuizNewFragment());
        final TextView tvHot = mBingding.tvHot;
        tvHot.setTag(new QuizHotFragment());
        final TextView tvConcern = mBingding.tvConcern;
        tvConcern.setTag(new QuizConcernFragment());
        final TextView tvMine = mBingding.tvMine;
        tvMine.setTag(new QuizMineFragment());

        final ViewGroup vRoot = (ViewGroup) mBingding.getRoot();
        vRoot.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {

                vRoot.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                for(int i = 0; i < vRoot.getChildCount(); i++) {
                    vRoot.getChildAt(i).getLayoutParams().width = vRoot.getWidth();
                }

            }
        });


        vSel = tvNew;
        final BaseFragment tag = (BaseFragment) vSel.getTag();
        tvTitle.setText(tag.getTitle());

        final FragmentManager fm = getFragmentManager();
        final int layFrag = R.id.layFrag;
        fm.beginTransaction().replace(layFrag, tag).commit();

        View.OnClickListener onClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mDropDownMenu.dismiss();
                if(vSel != v) {
                    TextView tv = (TextView) v;

                    tvTitle.setText(tv.getText());

                    final FragmentTransaction transaction = fm.beginTransaction();
                    final BaseFragment tag = (BaseFragment) tv.getTag();

                    transaction.replace(layFrag, tag).commit();

                    //transaction.hide((Fragment) vSel.getTag()).commit();

                    vSel.setSelected(false);
                    tv.setSelected(true);

                    vSel = tv;
                }

            }
        };

        tvNew.setOnClickListener(onClick);
        tvHot.setOnClickListener(onClick);
        tvConcern.setOnClickListener(onClick);
        tvMine.setOnClickListener(onClick);

        mDropDownMenu = new PopupWindow(vPop, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mDropDownMenu.setFocusable(true);
        mDropDownMenu.setOutsideTouchable(true);
        mDropDownMenu.setBackgroundDrawable(new BitmapDrawable());
        mDropDownMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mArrowRotate.clearAnimation();
                mArrowRotate.startAnimation(mReverseAnimation);
            }
        });

        vPop.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        menuWidth = vPop.getMeasuredWidth();

    }
    private void createAnimation() {
        mRotateAnimation = new RotateAnimation(0, 180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mRotateAnimation.setInterpolator(new LinearInterpolator());
        mRotateAnimation.setDuration(mRotateDuration);
        mRotateAnimation.setFillAfter(true);

        mReverseAnimation = new RotateAnimation(180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        mReverseAnimation.setInterpolator(new LinearInterpolator());
        mReverseAnimation.setDuration(mRotateDuration);
        mReverseAnimation.setFillAfter(true);
    }
    private View.OnClickListener createOnClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int viewId = v.getId();
                if(R.id.fl_find_search == viewId) {
                    startActivityFromFragment(SearchActivity.class);
                } else if(R.id.ll_filter_title == viewId) {
                    showDropDownMenu();
                } else if(R.id.fl_head_action == viewId) {
                    startActivityFromFragment(NewProblemsActivity.class);
                }
            }
        };
    }
    private void showDropDownMenu() {

        mArrowRotate.clearAnimation();
        mArrowRotate.startAnimation(mRotateAnimation);
        int xOff = (mTileLayout.getWidth() - menuWidth) / 2;
        mDropDownMenu.showAsDropDown(mTileLayout, xOff, 0);
    }
    public void onEvent(FindSwitchEvent event) {
        int mSwitchEvent = event.getEvent();
    }

    public void onEvent(LongTaskEvent event) {
        switch(event.getEvent()) {
            case LongTaskEvent.LONG_TASK_QUESTION_SHOW:
                //                mDataBinding.btnLongtask.setVisibility(View.VISIBLE);
                ((AppContext) getContext().getApplicationContext()).createView();
                break;

            case LongTaskEvent.LONG_TASK_QUESTION_COMPLETE:
                LongTask.getInstance().deleteTaskList("问题");
                if(LongTask.getInstance().getListList().size() == 0) {
                    mDataBinding.btnLongtask.setVisibility(View.GONE);
                    ((AppContext) getContext().getApplicationContext()).removeView();
                    ((AppContext) getContext().getApplicationContext()).createViews();
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            // do something
                            ((AppContext) getContext().getApplicationContext()).removeViews();
                        }

                    }, 2 * 1000);
                }
                break;
            case LongTaskEvent.LONG_TASK_ANSWER_COMPLETE:
                LongTask.getInstance().deleteTaskList("回答");
                if(LongTask.getInstance().getListList().size() == 0) {
                    mDataBinding.btnLongtask.setVisibility(View.GONE);
                    ((AppContext) getContext().getApplicationContext()).removeView();
                    ((AppContext) getContext().getApplicationContext()).createViews();
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            // do something
                            ((AppContext) getContext().getApplicationContext()).removeViews();
                        }

                    }, 2 * 1000);
                }
                break;
            case LongTaskEvent.LONG_TASK_QUESTION_EDIT_COMPLETE:
                LongTask.getInstance().deleteTaskList("编辑问题");
                if(LongTask.getInstance().getListList().size() == 0) {
                    mDataBinding.btnLongtask.setVisibility(View.GONE);
                    ((AppContext) getContext().getApplicationContext()).removeView();
                    ((AppContext) getContext().getApplicationContext()).createViews();
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            // do something
                            ((AppContext) getContext().getApplicationContext()).removeViews();
                        }

                    }, 2 * 1000);
                }
                break;
            case LongTaskEvent.LONG_TASK_ANSWER_EDIT_COMPLETE:
                LongTask.getInstance().deleteTaskList("编辑问题");
                if(LongTask.getInstance().getListList().size() == 0) {
                    mDataBinding.btnLongtask.setVisibility(View.GONE);
                    ((AppContext) getContext().getApplicationContext()).removeView();
                    ((AppContext) getContext().getApplicationContext()).createViews();
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            // do something
                            ((AppContext) getContext().getApplicationContext()).removeViews();
                        }

                    }, 2 * 1000);
                }
                break;
            case LongTaskEvent.LONG_TASK_QUESTION_ERROR:
                LongTask.getInstance().deleteTaskList("问题");
                mDataBinding.btnLongtask.setVisibility(View.GONE);
                ((AppContext) getContext().getApplicationContext()).removeView();
                break;
            case LongTaskEvent.LONG_TASK_ANSWER_ERROR:
                LongTask.getInstance().deleteTaskList("回答");
                mDataBinding.btnLongtask.setVisibility(View.GONE);
                ((AppContext) getContext().getApplicationContext()).removeView();
                break;
            case LongTaskEvent.LONG_TASK_QUESTION_EDIT_ERROR:
                LongTask.getInstance().deleteTaskList("编辑问题");
                mDataBinding.btnLongtask.setVisibility(View.GONE);
                ((AppContext) getContext().getApplicationContext()).removeView();
                break;
            case LongTaskEvent.LONG_TASK_ANSWER_EDIT_ERROR:
                LongTask.getInstance().deleteTaskList("编辑回答");
                mDataBinding.btnLongtask.setVisibility(View.GONE);
                ((AppContext) getContext().getApplicationContext()).removeView();
                break;
            case LongTaskEvent.LONG_TASK_CLICK:
                //                LongTaskList.start(getContext(),mTaskList);
                startActivityFromFragment(LongTaskList.class);
                break;
            case LongTaskEvent.LONG_TASK_FINISH:
                LongTask.getInstance().deleteTaskList();
                ((AppContext) getContext().getApplicationContext()).removeView();
        }
    }

}
